const v = require('../Model/ConstValue');
import AudioUtils from "../Utils/AudioUtils";

cc.Class({
    extends: cc.Component,

    properties: {
        bombWhite: {
            type: cc.Prefab,
            default: null
        },
        crushEffect: {
            type: cc.Prefab,
            default: null
        },
        audioUtils: {
            type: AudioUtils,
            default: null
        },
        scoreLabel: cc.Label,
        score: 0,
    },

    // use this for initialization
    onLoad: function () {
        this.score = 0;
    },

    playEffects(effectQueue) {
        if (!effectQueue || effectQueue.length <= 0) {
            return;
        }
        let soundMap = {}; //某一时刻，某一种声音是否播放过的标记，防止重复播放
        effectQueue.forEach(cmd => {
            let delayTime = cc.delayTime(cmd.playTime);
            let callFunc = cc.callFunc(function () {
                let instantEffect = null;
                let animation = null;
                if (cmd.action == "crush") {
                    instantEffect = cc.instantiate(this.crushEffect);
                    animation = instantEffect.getComponent(cc.Animation);
                    animation.play("effect");
                    this.updateScore(this.score + v.CELL_WORTH); // 动物消失后更新分数
                    !soundMap["crush" + cmd.playTime] && this.audioUtils.playEliminate(cmd.step);
                    soundMap["crush" + cmd.playTime] = true;
                }
                else if (cmd.action == "rowBomb") {
                    instantEffect = cc.instantiate(this.bombWhite);
                    animation = instantEffect.getComponent(cc.Animation);
                    animation.play("effect_line");
                }
                else if (cmd.action == "colBomb") {
                    instantEffect = cc.instantiate(this.bombWhite);
                    animation = instantEffect.getComponent(cc.Animation);
                    animation.play("effect_col");
                }
                if(instantEffect && animation) {
                    instantEffect.x = v.CELL_WIDTH * (cmd.pos.y - 0.5);
                    instantEffect.y = v.GRID_HEIGHT - (v.OFFSET_Y+ v.CELL_HEIGHT)*(cmd.pos.x-0.5);
                    instantEffect.parent = this.node;
                    animation.on("finished", function () {
                        instantEffect.destroy();
                    }, this);
                }
            }, this);
            this.node.runAction(cc.sequence(delayTime, callFunc));
        }, this);
    },

    // 更新分数
    updateScore(number) {
        this.score = number;
        this.scoreLabel.string = "分数： " + number;
    },
});
